<template>
  <div class="dialog">
    <el-dialog :title="'设备台账' + titleText" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false" @close="cancel">
      <el-form v-if="showForm" ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="所属设备型号：" prop="equModelCode" class="w50p">
          <el-select v-model="formData.equModelCode" filterable clearable>
            <el-option v-for="item in equModelArr" :key="item.equModelCode" :label="item.modelName" :value="item.equModelCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称：" prop="equipmentName" class="w50p">
          <el-input v-model="formData.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="品牌：" prop="brand" class="w50p">
          <el-input v-model="formData.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="出厂序号：" prop="serialNumber" class="w50p">
          <el-input v-model="formData.serialNumber" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="生产日期：" prop="produceDate" class="w50p">
          <el-date-picker v-model="formData.produceDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="生产企业：" prop="manufacturer" class="w50p">
          <el-input v-model="formData.manufacturer" placeholder="请输入生产企业" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark" class="w50p">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="left">购置信息</el-divider>
        <el-form-item label="购置日期：" prop="purchaseDate" class="w50p">
          <el-date-picker v-model="formData.purchaseDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择购置日期" />
        </el-form-item>
        <el-form-item label="质保期：" prop="sellByDate" class="w50p">
          <el-input v-model.number="formData.sellByDate" placeholder="请输入质保期">
            <template slot="append">月</template>
          </el-input>
        </el-form-item>
        <el-divider content-position="center">
          <span class="pointer" @click="more = !more">{{ more ? '收起' : '显示全部' }}</span>
        </el-divider>
        <template v-if="more">
          <el-form-item label="质保日期：" prop="warrantyDate" class="w50p">
            <el-date-picker v-model="formData.warrantyDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择生产日期和输入质保期" />
          </el-form-item>
          <el-form-item label="供应商：" prop="taxpayerNumber" class="w50p">
            <el-input v-model="formData.taxpayerNumber" placeholder="请输入供应商" />
          </el-form-item>
          <el-form-item label="补贴金额：" prop="purchaseSubsidy" class="w50p">
            <el-input v-model.trim="formData.purchaseSubsidy" type="number" clearable placeholder="请输入补贴金额" />
          </el-form-item>
          <el-form-item label="购置金额：" prop="purchaseAmount" class="w50p">
            <el-input v-model="formData.purchaseAmount" clearable placeholder="请输入购置金额" />
          </el-form-item>
          <el-form-item label="购置备注：" prop="purchaseRemark" class="w50p"> <el-input v-model="formData.purchaseRemark" type="textarea" placeholder="请输入购置备注" /> </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button :loading="saveLoading" type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 组件
// Api 接口
import EquipmentApi from '@/api/processing-management/equip-manage/equipment/index';

export default {
  name: '',
  components: {},
  props: {
    value: Boolean,
    // 弹框名称
    titleText: {
      type: String,
      default: '添加'
    },
    nowChanceStau: {
      type: String,
      default: ''
    },
    editObject: {
      type: Object,
      default: null
    },
    equModelArr: {
      type: [Array],
      default: () => {
        return [];
      }
    },
    selectCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showForm: false,
      more: false,
      lnglat: [],
      // 展示
      formDataDef: {
        equModelCode: '',
        equipmentName: '',
        brand: '',
        serialNumber: '',
        produceDate: '',
        manufacturer: '',
        remark: '',
        purchaseDate: '',
        sellByDate: '',
        warrantyDate: '',
        taxpayerNumber: '',
        purchaseSubsidy: '',
        purchaseAmount: '',
        purchaseRemark: ''
      },
      formData: {},
      rules: {
        equModelCode: [
          {
            required: true,
            message: '请选择设备型号',
            trigger: ['blur', 'change']
          }
        ],
        equipmentName: [
          {
            required: true,
            message: '请输入设备名称',
            trigger: ['blur', 'change']
          }
        ],
        produceDate: [
          {
            required: true,
            message: '请选择生产日期',
            trigger: ['blur', 'change']
          }
        ],
        purchaseDate: [
          {
            required: true,
            message: '请选择购置日期',
            trigger: ['blur', 'change']
          }
        ],
        sellByDate: [
          {
            required: true,
            message: '请输入质保期',
            trigger: ['blur', 'change']
          }
        ]
      },
      showDialog: false,
      statusArr: [
        {
          name: '启用',
          id: 'ENABLE'
        },
        {
          name: '废弃',
          id: 'DISCARD'
        },
        {
          name: '维修中',
          id: 'REPAIRING'
        },
        {
          name: '禁用',
          id: 'DISABLE'
        }
      ],
      saveLoading: false
    };
  },

  watch: {
    value(v) {
      this.showDialog = v;
      if (!v) {
        setTimeout(() => {
          this.$refs['ruleForm'].resetFields();
          this.showForm = false;
          this.formData = JSON.parse(JSON.stringify(this.formDataDef));
        }, 250);
      } else {
        this.showForm = true;
      }
    },
    nowChanceStau(v) {
      if (v === 'add') {
        this.formData.equipmentTypeCode = this.editObject.equipmentTypeCode;
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate();
        });
      } else if (v === 'edit') {
        const { editObject, formData } = this;
        for (const key in formData) {
          if (editObject[key]) {
            this.formData[key] = editObject[key];
          }
        }
      }
    },
    'formData.purchaseDate': {
      deep: true,
      handler(v) {
        if (v && this.formData.sellByDate) {
          var dt = new Date(v);
          dt.setMonth(dt.getMonth() + this.formData.sellByDate);
          //  document.write( dt );
          this.$set(this.formData, 'warrantyDate', this.dateToFormatTwo(dt));
        } else {
          this.$set(this.formData, 'warrantyDate', '');
        }
      }
    },
    'formData.sellByDate': {
      deep: true,
      handler(v) {
        if (v && this.formData.purchaseDate) {
          var dt = new Date(this.formData.purchaseDate);
          dt.setMonth(dt.getMonth() + v);
          //  document.write( dt );
          this.$set(this.formData, 'warrantyDate', this.dateToFormatTwo(dt));
        } else {
          this.$set(this.formData, 'warrantyDate', '');
        }
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    save(formData) {
      const { editObject, selectCode } = this;
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          if (editObject) {
            // // 编辑接口
            // var index = this.statusArr.findIndex(a => a.name === this.formData.status);
            // if (index !== -1) {
            //   this.formData.status = this.statusArr[index].id;
            // }
            // // const { data: res } = await equipStandingBookApi.queryBeOccupied(this.formData.equipmentName);
            // // if (res === false) {
            // equipStandingBookApi
            //   .edit({
            //     ...this.formData,
            //     organizationNo: sessionStorage.organizationNo
            //   })
            //   .then(res => {
            //     if (res.code === 1) {
            //       this.$message.success('修改成功！');
            //       this.close();
            //     }
            //   });
            // // } else {
            // //   this.$message.error("该设备名称已存在，请重新输入！")
            // // }
          } else {
            this.saveLoading = true;
            // 新增接口
            EquipmentApi.addEquipment({
              ...this.formData,
              equipmentTypeCode: selectCode
            }).then(res => {
              this.saveLoading = false;
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.$emit('reflash');
                this.close();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      this.$emit('input', false);
    },
    cancel() {
      this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      this.$emit('input', false);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__wrapper .el-dialog .el-dialog__body .el-form .el-form-item .el-form-item__label {
  min-width: 160px !important;
}
::v-deep {
  .el-divider__text {
    background-color: #f0f3f7;
  }
}
</style>
